package com.xy.hms.controller;


import com.xy.hms.model.User;
import com.xy.hms.service.UserServiceI;
import com.xy.hms.util.DataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.ListUtils;

import javax.jws.WebParam;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author xiaye
 * @create 2020-02-26-16:11
 */

@Api(tags = "用户登录控制类")
@Controller
public class UserController {


    @Autowired
    UserServiceI userServiceI;




    /**
     * @param toConfirmUser 前台传来的登录信息
     * @return 返回错误信息
     */
    @ApiOperation("登录控制")
    @PostMapping(value = "/user")
    public String userLogin(User toConfirmUser, Model model, HttpSession session,String rememberMe) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken usernamePasswordToken =
                new UsernamePasswordToken(toConfirmUser.getUsername(), toConfirmUser.getPassword());

        if (rememberMe!=null && "1".equals(rememberMe)){
            usernamePasswordToken.setRememberMe(true);
        }


        try {
            subject.login(usernamePasswordToken);//执行登陆方法  ，没有异常，登陆成功
            session.setAttribute("loginUser", toConfirmUser);  //往session里放一个登录的用户信息
            String roleName = userServiceI.getRoleName(toConfirmUser);  //登录用户的角色名称
            session.setAttribute("roleName",roleName);

            //消除没有权限的提示
            session.removeAttribute("requireLogin");

            return "redirect:/rooms";
        } catch (UnknownAccountException e) {  //用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            //密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }


//        try {
//            //登录成功
//            User loginUser = userServiceI.userLogin(toConfirmUser);
//            session.setAttribute("loginUser", loginUser);
//            //消除没有权限的提示
//            session.removeAttribute("requireLogin");
//
//            if (null != session.getAttribute("msg")) session.removeAttribute("msg");
//            return "redirect:/rooms";
//
//            //账号密码正确，重定向到主页
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            session.setAttribute("msg", e.getMessage());
//            return "login";
//
//        }


    }


    @GetMapping(value = "logout")
    public String logout(HttpSession session) {
        //退出登录
//        session.removeAttribute("loginUser");

        //获取用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "redirect:/login";

    }

    @GetMapping("/unAuth")
//    @ResponseBody
    public String noAuthorzation(){
        return "NoAuthPage";
    }


    @PostMapping("/user/register")
    public String register(String username, String password, String pass2,
                           HttpSession session,
                           Model model){

        if (password.equals(pass2)){
            //两次密码相同,注册成功
            String msg = userServiceI.addUser(username, password);
            User user = new User();
            user.setUsername(username);
            User userByCondition = userServiceI.getUserByCondition(user);
            //默认都设置成普通会员
            int i = userServiceI.addAuth(userByCondition.getId());

            model.addAttribute("registerSuccess",msg);
        }else {
            //注册失败
            model.addAttribute("registerError","密码不一致！");
        }
        return "sign_up";
    }


    //查询所有的带角色的用户
    @GetMapping("/user/showAuths")
    public String showAuths(Model model){
        List<User> userWithAuth = userServiceI.getUserWithAuth();
        if (userWithAuth.isEmpty()){
            //查询为空
             model.addAttribute("msg","后台出小差啦。。。");
        }else {
            model.addAttribute("userWithAuth",userWithAuth);
        }
        return "user/all_users";
    }


    //查询指定编号的用户的角色信息
    @GetMapping("/user/getUserAuth/{id}")
    @ResponseBody
    public DataUtil getUserAuthById(DataUtil dataUtil,@PathVariable("id")Integer id){

        User user= userServiceI.getUserWithAuthById(id);
        dataUtil.setData(Arrays.asList(user));
        return dataUtil;
    }

    //修改对应用户的角色
    @PutMapping("/user/updateUserAuth")
    @ResponseBody
    public DataUtil updateUserAuth(User user,Integer rid,DataUtil dataUtil){
        //修改用户
        int userStatus = userServiceI.updateUser(user);
        int userRoleStatus = userServiceI.updateUserRole(user.getId(), rid);

        if (userStatus!=0 && userRoleStatus!=0){
            //修改成功
            dataUtil.setResult(true);
            dataUtil.setMsg("修改成功");
        }else {
            dataUtil.setResult(false);
            dataUtil.setMsg("修改失败！");
        }
        return dataUtil;
    }


    @PutMapping("/user/changePwd")
    @ResponseBody
    public DataUtil changePassword(DataUtil dataUtil,User user,String newPassword){
        User userByCondition = userServiceI.getUserByCondition(user);
        if (userByCondition!=null && user.getPassword().equals(userByCondition.getPassword())){
            User newUser = new User();
            newUser.setUsername(user.getUsername());
            newUser.setPassword(newPassword);
            newUser.setId(userByCondition.getId());

            int i = userServiceI.updateUser(newUser);

            if (i!=0){
                dataUtil.setResult(true);
                dataUtil.setMsg("修改成功");
            }else {
                dataUtil.setResult(false);

            }
        }else {
            dataUtil.setResult(false);
            dataUtil.setMsg("当前密码不一致");

        }
        return dataUtil;
    }



}
